package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.BusinesssellerBaseInfo;
import com.sl.au.entity.BussinessInspection;
import com.sl.au.entity.Option;
import com.sl.au.service.BusinesssellerBaseInfoService;
import com.sl.au.service.BussinessInspectionService;
import com.sl.au.service.OptionService;
import com.sl.utils.MsgHelper;

/**
 * 商户巡检
 * 
 * @author heguangchuan
 *
 */
@RestController
@RequestMapping(value = "/ui/bussinessInspection")
public class BussinessInspectionController extends BaseController {

	@Autowired
	private BussinessInspectionService bussinessInspectionService;
	@Autowired
	private BusinesssellerBaseInfoService businesssellerBaseInfoService;
	@Autowired
	private OptionService optionService;

	@RequestMapping("/findOptsByGroup")
	public MsgHelper findOptsByGroup() {

		return MsgHelper.success()//
				.put("noneOpt", optionService.getRepository().findByGroup("无"))//
				.put("environment", optionService.getRepository().findByGroup("环境卫生"))//
				.put("cityOrder", optionService.getRepository().findByGroup("市容秩序"))//
				.put("greenCondition", optionService.getRepository().findByGroup("绿化美化"));
	}

	@RequestMapping(value = "/listAllSellers", method = RequestMethod.GET)

	public MsgHelper listAllSeller() {
		List<BusinesssellerBaseInfo> infos = businesssellerBaseInfoService.findAll();
		return MsgHelper.success().put("sellers", infos);
	}

	@RequestMapping("/findById/{id}")

	public MsgHelper findById(@PathVariable("id") String id) {
		BussinessInspection info = bussinessInspectionService.findById(id);
		return MsgHelper.success().put("info", info);
	}

	@RequestMapping("/pageOnPhone")
	public MsgHelper getPageInfoOnPhone() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");// 这个商户的id
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}

		// 初始化页面
		List<BussinessInspection> uncheckedInfo = bussinessInspectionService.findByTimeAndUncheck(0, 30, identify, null,
				null);
		List<BussinessInspection> checkedInfo = bussinessInspectionService.findByCheck(0, 30, identify, null, null);

		return MsgHelper.success().put("uncheckedInfo", uncheckedInfo).put("checkedInfo", checkedInfo);
	}

	/**
	 * 保存巡检信息
	 * 
	 * @param bussinessInspection
	 *            表单提交过来的数据
	 * @return 构建的json数据
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)

	public MsgHelper save(BussinessInspection bussinessInspection,
			@RequestParam(value = "file", required = false) MultipartFile file) {

		String bussinessId = request.getParameter("bussinessId");
		String optionId = request.getParameter("optionId");
		// String environmetId = request.getParameter("environmetId");
		String enviromentIds = request.getParameter("enviromentIds");

		// 关联非表单数据
		bussinessInspection.setInspectDate(new Date());
		bussinessInspection.setUser(getMyAccount().getUser());
		bussinessInspection
				.setBusinesssellerBaseInfo(businesssellerBaseInfoService.findByBussinessSellerId(bussinessId));
		bussinessInspection.setInspectCondition(optionService.getRepository().findOne(optionId));
		// bussinessInspection.setEnvironmentOpt(optionService.getRepository().findOne(environmetId));
		List<String> ids = new ArrayList<>();
		for (String id : enviromentIds.split(",")) {
			ids.add(id);
		}
		HashSet<Option> opts = new HashSet<Option>(optionService.getRepository().findAll(ids));
		bussinessInspection.setEnvironmentOpt(opts);
		System.out.println("file:" + file);
		// 获取当前图片的存储路径
		// 或许是插件原因 即使不上传文件对象也不会为null，但是文件名是空字符串
		if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
			// 注意路径的构建
			String url = getUploadFilePath(this.fileUploadPath, "img/inspection", file);
			bussinessInspection.setPictureAddr(url);
		}

		bussinessInspectionService.save(bussinessInspection);

		return MsgHelper.success();
	}

	/**
	 * 
	 * @param map
	 *            存放到页面的数据
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.GET)
	public ModelAndView saveUI(Map<String, Object> map) {
		map.put("id", "");
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.setViewName("mobile/bussinessInspection/saveOrUpdateOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("options", optionService.getRepository().findByGroup("巡检状况"));
			return modelAndView;
		} else {
			return createLayoutView("bussinessInspection/saveOrUpdate");
		}
	}

	/**
	 * 
	 * @param id
	 *            到修改页面传的id
	 * @param map
	 *            存放到页面所需要的数据
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdate/{id}", method = RequestMethod.GET)
	public ModelAndView updateUI(@PathVariable("id") String id, Map<String, Object> map) {
		map.put("id", id);

		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.setViewName("mobile/bussinessInspection/saveOrUpdateOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("options", optionService.getRepository().findByGroup("巡检状况"));
			return modelAndView;
		} else {
			return createLayoutView("bussinessInspection/saveOrUpdate");
		}
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)

	public MsgHelper delete(@PathVariable(value = "id") String id) {
		bussinessInspectionService.deleteById(id);
		return MsgHelper.success();
	}

	/**
	 * 获取商户巡检分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/page", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		List<BussinessInspection> inspections = null;
		String key = request.getParameter("key");
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		// 移动端
		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			// 只显示最新的10页
			inspections = bussinessInspectionService.getInspections(0, 10, identify, null, null);
		} else {
			// PC端

			if (StringUtils.hasText(key)) {
				inspections = bussinessInspectionService.getInspections(start, length, key, null, null);
			} else {
				inspections = bussinessInspectionService.getPage(start, length, null, null, null);
			}
		}

		int count = bussinessInspectionService.getCount(key);
		map.put("data", inspections);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 进入巡检首页
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {
		String device = request.getParameter("device");
		String url = request.getParameter("url");
		String identify = request.getParameter("identify");
		// 移动端
		if (StringUtils.hasText(device) && this.DEVICE.equals(device)) {
			// 移动端访问的首页
			modelAndView.setViewName("mobile/bussinessInspection/indexOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("device", device);
			modelAndView.addObject("url", url);

		} else {
			// PC端
			modelAndView = createLayoutView("bussinessInspection/bussinessInspection");
		}
		return modelAndView;
	}
}
